var $newMemberTaable = $('#newMember');//新单会员表格

$(function () {
    // 时间选择器放在第一时间加载
    timeComponentInit();

    memberPercentageData()
    //需要时间参数的放在时间组件加载后添加
    customerIntentionInit();
    meberData($('#startTm').val(), $('#endTm').val())

})

function timeComponentInit(){
    var endTime = new Date().FormatFMT("yyyy-MM")
    var startTime = GetPreMonthDay(new Date().FormatFMT("yyyy-MM"), 6)
    $('#startTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: startTime
    });
    $('#endTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: endTime
    });


    $('#currentTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: endTime
    });

}

//防止表头与表格不对齐
$(window).resize(function () {
    $newMemberTaable.bootstrapTable('resetView');
});


// 方法已作废
function selTime(time) {
    if (time == 'topYear') {//上年
        $('.topYear').addClass('active-second');
        $('.year').removeClass('active-second');
        $("#clientDataType").val("topYear");
        meberData(0)
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.topYear').removeClass('active-second');
        $("#clientDataType").val("year");
        meberData(1)
    }
}

function customTimeQuery() {
    meberData($('#startTm').val(), $('#endTm').val())
}

function meberData(startDate, endDate) {
    var startInt = startDate.replace(/-/g, '/');
    var endInt = endDate.replace(/-/g, '/');

    if (endInt < startInt){
        alert('开始时间不得大于结束时间,请正确选择起止时间')
    }

    $.ajax({
        type: 'get',
        url: '/newMemberAnalyse/getNewMemberMonthlyStatistics',
        dataType: "json",
        // contentType: "application/json;charset=utf-8",
        data: {
            startDate: startDate,
            endDate: endDate
        },
        success: function (result) {
            if (result.code == '000000') {
                var data = result.data;
                var memberList = [];
                var dealLIst = [];
                var timeList = [];
                var newList = [];
                $.each(data, function (index, item) {
                    memberList.push(item.memberRecruitmentRate);
                    dealLIst.push(item.dealCustomersNumber);
                    timeList.push(item.yearMonth);
                    newList.push(item.newNumberCount);

                })
                // echartClientRate('member',timeList,memberList,dealLIst,newList,'','会员招募率','成交客户数','新会员数')
                echartClientRate('member', timeList, "", dealLIst, newList, '', '', '成交客户数', '新会员数')
                // memberInit('member',memberList,dealLIst,timeList,newList)

            }
        },
        error: function () {
            alert('请求失败')
        }
    });
}

function memberPercentageData() {
    $.ajax({
        type: 'get',
        url: '/newMemberAnalyse/getPercentageQuotaStatistics',
        dataType: "json",
        // contentType: "application/json;charset=utf-8",
        data: {},
        success: function (result) {
            if (result.code == '000000') {
                var data = result.data;
                console.log(data, 100)
                memberPercentageInit('memberPercentage', data)
            }
        },
        error: function () {
            alert('请求失败')
        }
    });
}

/**
 * 新会员招募率图表
 */
// function memberInit(id,memberList,dealLIst,timeList,newList){
//     let dom = document.getElementById(id);
//     let myChart = echarts.init(dom);
//     let option = {
//         "tooltip": {
//             "trigger": "axis",
//             "axisPointer": {
//                 "type": "shadow",
//                 textStyle: {
//                     color: "rgba(0,0,0,0.5)"
//                 }
//
//             },
//         },
//         "calculable": true,
//         "xAxis": [{
//             "type": "category",
//             "axisLine": {
//                 lineStyle: {
//                     color: 'rgba(0,0,0,0.5)'
//                 }
//             },
//             "splitLine": {
//                 "show": false
//             },
//             "axisTick": {
//                 "show": false
//             },
//             "splitArea": {
//                 "show": false
//             },
//             "axisLabel": {
//                 "interval": 0,
//                 color:'rgba(0,0,0,0.5)',
//                 fontSize:14
//             },
//             "data": timeList,
//         }],
//         "yAxis": [{
//             "type": "value",
//             "splitLine": {
//                 "show": false
//             },
//             "axisLine": {
//                 "show": false
//             },
//             "axisTick": {
//                 "show": false
//             },
//             "axisLabel": {
//                 "interval": 0,
//                 color:'rgba(0,0,0,0.5)',
//                 fontSize:14
//
//             },
//             "splitArea": {
//                 "show": false
//             },
//
//         }],
//         "series": [{
//             "name": "会员招募率",
//             "type": "bar",
//             "stack": "总量",
//             "barMaxWidth": 20,
//             // "barGap": "10%",
//             "itemStyle": {
//                 "normal": {
//                     "color":
//                         {
//                             type: 'linear',
//                             x: 0,
//                             y: 0,
//                             x2: 0,
//                             y2: 1,
//                             colorStops: [{
//                                 offset: 0,
//                                 color: 'rgba(35, 157, 250, 1)' // 0% 处的颜色
//                             }, {
//                                 offset: 1,
//                                 color: 'rgba(35, 157, 250, 0)' // 100% 处的颜色
//                             }],
//                             global: false // 缺省为 false
//                         }
//                 }
//             },
//             "data": memberList,
//         },
//
//             {
//                 "name": "当月成交客户数",
//                 "type": "bar",
//                 "stack": "总量",
//                 "itemStyle": {
//                     "normal": {
//                         "color": {
//                             type: 'linear',
//                             x: 0,
//                             y: 0,
//                             x2: 0,
//                             y2: 1,
//                             colorStops: [{
//                                 offset: 0,
//                                 color: 'rgba(35, 250, 187, 1)' // 0% 处的颜色
//                             }, {
//                                 offset: 1,
//                                 color: 'rgba(35, 250, 187, 0)' // 100% 处的颜色
//                             }],
//                             global: false // 缺省为 false
//                         },
//                         "barBorderRadius": 0
//                     }
//                 },
//                 "data": dealLIst
//             }, {
//                 "name": "当月新会员数",
//                 "type": "line",
//                 symbolSize: 2,
//                 symbol: 'circle',
//                 "itemStyle": {
//                     "normal": {
//                         "color": 'rgba(255, 196, 53, 1)',
//                         "barBorderRadius": 0,
//                     }
//                 },
//                 lineStyle:{
//                     normal:{
//                         width:4,
//                         color:{
//                             type: 'linear',
//                             x: 0,
//                             y: 0,
//                             x2: 0,
//                             y2: 1,
//                             colorStops: [{
//                                 offset: 0,
//                                 color: 'rgba(255, 67, 2, 1)' // 0% 处的颜色
//                             }, {
//                                 offset: 1,
//                                 color: 'rgba(255, 196, 53, 1)' // 100% 处的颜色
//                             }],
//                             global: false // 缺省为 false
//                         }
//                     }
//                 },
//                 "data": newList
//             },
//         ]
//     };
//     myChart.setOption(option);
//     window.addEventListener("resize",function(){
//         myChart.resize();
//     });
// }

/**
 * 新会员招募率占比
 */
function memberPercentageInit(id, data) {
    let memberdom = document.getElementById(id);
    let memberChart = echarts.init(memberdom);
    let option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {

            left: 'center'
        },
        color: ['#6699FF', '#52CCA3', '#B3CDFF'],
        series: [
            {
                name: '会员占比',
                type: 'pie',
                radius: '70%',
                data: [
                    {value: data.memberQuota, name: '会员新单'},
                    {value: data.renewMemberQuota, name: '续费会员'},
                    {value: data.noMemberQuota, name: '非会员'},
                ],
                label: {
                    show: false,
                    position: 'inner',
                },
                emphasis: {
                    itemStyle: {
                        // shadowBlur: 10,
                        // shadowOffsetX: 2,
                        // shadowColor: 'rgba(255, 255, 255, 1)'
                        borderColor: '#fff',
                        borderWidth: 4
                    }
                }
            }
        ]
    };
    memberChart.setOption(option);
    window.addEventListener("resize", function () {
        memberChart.resize();
    });
}

/**
 *新单会员统计表格初始化
 */
function customerIntentionInit() {
    //先销毁表格
    $newMemberTaable.bootstrapTable('destroy');
    $newMemberTaable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/newMemberAnalyse/getNewSingleMemberStatistics',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'invoiceTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'formId', visible: false},
            // {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle'},
            {title: '所属业务员', field: 'userName', align: 'left', valign: 'middle'},
            {title: '成交额度', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '产品名称', field: 'orderDetailName', align: 'left', valign: 'middle'},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.yearMonth = $('#currentTm').val(); //yearMonth
    params.contractType = $('#orderType').val();//订单类型 2：会员新单 4：会员续费
    return params;
}

function echartClientRate(id, xdata, ydata0, ydata1, ydata2, title_text, y_name0, y_name1, y_name2) {
    //客户分析转化表
    let clientRate = document.getElementById(id)
    let myChart = echarts.init(clientRate);
    line_option.xAxis[0].data = xdata
    line_option.series[0].data = ydata0
    //
    line_option.series[1].data = ydata1
    line_option.series[2].data = ydata2
    line_option.title.text = title_text
    line_option.series[0].name = y_name0
    line_option.series[1].name = y_name1
    line_option.series[2].name = y_name2


    myChart.setOption(line_option);
    window.onresize = myChart.resize;
    /**/
}

const color = ['#6699ff', "#52cca3", '#caed8b']
var line_option = {
    title: {
        text: '新增客户/成交客户',
        left: '5%',
        top: '3%',
        textStyle: {
            color: '#999999',
            fontSize: '12',
        },
    },
    legend: {
        left: 'center',
        top: '30',
        data: ['成交客户数', '新会员数', '会员招募率（删除括弧及包含内容生效）']
    },
    tooltip: {
        trigger: 'axis',
        /*formatter: function (params) {
            var html = '<div class="tooltip-box">';
            html += params[0].axisValue + '<br>';
            html += '<span class="tooltip-icon tips-1"></span>' + params[0].seriesName + ': ' + parseInt(params[0].data * 100) + '%<br>';
            html += '<span class="tooltip-icon tips-2"></span>' + params[1].seriesName + ': ' + params[1].data + '<br>';
            html += '<span class="tooltip-icon tips-3"></span>' + params[2].seriesName + ': ' + params[2].data + '</div>';
            return html;
        }*/
    },
    grid: {
        x: '3%',
        x2: '4%',
        y: '95',
        y2: '30',
        containLabel: true
    },
    xAxis: [{
        show: true,
        type: 'category',
        axisLine: {
            show: true,
            lineStyle: {
                color: 'rgba(83, 83, 83,0.1)',
            },
        },
        axisPointer: {
            type: 'shadow'
        },
        axisTick: {//坐标轴刻度相关设置。
            show: false,
        },
        axisLabel: {
            color: '#999999',
            margin: 20
        },
        splitLine: {
            show: false
        },
        boundaryGap: true,
        data: [],

    }],
    yAxis: [
        {
            type: 'value',
            name: '数量',
            interval: 20,
            nameTextStyle: {
                padding: [0, 13, 6, 0],
                align: 'right',
                color: '#333',
            },
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(83, 83, 83,0.1)'
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#999',
                    padding: [0, 6, 0, 0]
                }
            },
            splitArea: {
                areaStyle: {
                    color: 'rgba(255,255,255,.5)'
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#eee',
                    width: 1,
                    type: 'dashed'
                }
            }
        },
        {
            type: 'value',
            name: '比率',
            min: -1,
            max: 1,
            interval: 0.2,
            axisLabel: {
                textStyle: {
                    color: '#999',
                    padding: [0, 0, 0, 6]
                }
            },
            nameTextStyle: {
                padding: [0, 0, 6, 15],
                align: 'left',
                color: '#333',
            },
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(83, 83, 83,0.1)',
                }
            },
            splitArea: {
                areaStyle: {
                    color: 'rgba(255,255,255,.5)'
                }
            },
            splitLine: {
                show: false,
                lineStyle: {
                    color: '#eee',
                    width: 1,
                    type: 'dashed'
                }
            }
        },
    ],
    series: [
        {
            name: "会员招募率",
            type: "line",
            symbolSize: 2,
            symbol: 'circle',
            itemStyle: {
                "normal": {
                    "color": 'rgba(255, 196, 53, 1)',
                    "barBorderRadius": 0,
                }
            },
            lineStyle: {
                normal: {
                    width: 4,
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: 'rgba(255, 67, 2, 1)' // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: 'rgba(255, 196, 53, 1)' // 100% 处的颜色
                        }],
                        global: false // 缺省为 false
                    }
                }
            },
            yAxisIndex: 1,
            data: [],
        },
        {
            name: "成交客户数",
            type: "bar",
            // stack: "总量",
            barMaxWidth: 20,
            itemStyle: {
                normal: {
                    color:
                        {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: 'rgba(35, 157, 250, 1)' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: 'rgba(35, 157, 250, .5)' // 100% 处的颜色
                            }],
                            global: false // 缺省为 false
                        }
                }
            },
            data: []
        }, {
            name: "新会员数",
            type: "bar",
            // stack: "总量",
            barMaxWidth: 20,
            itemStyle: {
                normal: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: 'rgba(35, 250, 187, 1)' // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: 'rgba(35, 250, 187, .5)' // 100% 处的颜色
                        }],
                        global: false // 缺省为 false
                    },
                    barBorderRadius: 0
                },
            },
            data: []
        },
    ]
};
